import 'dart:async';

import 'package:flutter/material.dart';

class StreamDemo extends StatelessWidget {
  const StreamDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('StreamDemo'),
        elevation: 0.0,
      ),
      body: StreamDemoHome(),
    );
  }
}

class StreamDemoHome extends StatefulWidget {
  const StreamDemoHome({super.key});

  @override
  State<StreamDemoHome> createState() => _StreamDemoHomeState();
}

class _StreamDemoHomeState extends State<StreamDemoHome> {
  late StreamSubscription _streamSubscription;
  late StreamController _streamDemo;
  late StreamSink _sinkDemo;

  String _data = '...';

  @override
  void dispose() {
    _streamDemo.close();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    print('Create a stream');
    // Stream<String> _streamDemo = Stream.fromFuture(fetchData()); //马上触发 fetchData
    // _streamDemo = StreamController<String>();//需要 add 触发
    _streamDemo = StreamController.broadcast();//需要 add 触发
    _sinkDemo = _streamDemo.sink;

    print('Stream listening on a stream');
    _streamSubscription = _streamDemo.stream.listen(onData,onError: onError, onDone: onDone);
    _streamDemo.stream.listen(onDataTwo,onError: onError, onDone: onDone);
    print('Initialize completed');

  }

  void onDone(){
    print('onDone');
  }

  void onError(error){
    print('onError=> $error');
  }

  void onData(data){
    setState(() {
      _data =data;
    });
    
    print('$data');
  }

  void onDataTwo(data){
    print('onDataTwo: $data');
  }

  Future<String> fetchData() async{
    await Future.delayed(Duration(seconds: 3));
    // throw 'Something happen error';
    return 'hello ~';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(_data),
            StreamBuilder( //跟上面手动setdata 赋值 是一样的
              stream: _streamDemo.stream,
              initialData: '...',
              builder: ((context, snapshot) {
              return Text('${snapshot.data}');
            })),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FlatButton(child: Text('Add'),onPressed: _addDataToStream),
                FlatButton(child: Text('Pause'),onPressed: _pauseStream),
                FlatButton(child: Text('Resume'),onPressed: _resumeStream),
                FlatButton(child: Text('Cancel'),onPressed: _cancelStream),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void _pauseStream() {
    print('Pause subscription');
    _streamSubscription.pause();
  }

  void _resumeStream() {
    print('Resume subscription');
    _streamSubscription.resume();
  }

  void _cancelStream() {
    print('Cancel subscription');
    _streamSubscription.cancel();
  }

  void _addDataToStream() async {
    print('Add data to stream');

    String data = await fetchData();
    //_streamDemo.add(data); //功能相同
    _sinkDemo.add(data); //功能相同

  }
}